package com.yzh;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @author 于振晗
 * @title: TestDome4j03
 * @description: TODO DOM4j删除数据
 * @date 2020年09月08日
 * @path com.yzh
 */
public class TestDom4j04 {
    public static void main(String[] args) throws DocumentException, IOException {
        SAXReader reader = new SAXReader();
        File file = new File("Java_Xml/student1.xml");
        Document doc = reader.read(file);
        //获取文档的根节点
        Element rootElement = doc.getRootElement();
        List<Element> list = rootElement.elements();

        for (int i = 0; i < list.size(); i++) {
            Element element = list.get(i);
            Attribute id = element.attribute("id");
            if(id.getValue().equals("S222")){
                System.out.println("删除成功"+element.getName());
                list.remove(element);
                i--;
            }


        }
        OutputFormat outputFormat =OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(new FileWriter(file),outputFormat);
        xmlWriter.write(doc);
        xmlWriter.close();
    }
}
